package com.lagou.edu.mvcframework;

import com.lagou.edu.mvcframework.annotation.*;
import com.lagou.edu.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Pattern;

public class LgDispatcherServices extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>();

    //ioc容器
    private Map<String,Object> ioc = new HashMap<>();

    //存储url和method直接的映射关系
    //private Map<String,Method> handlerMapping = new HashMap<>();
    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求
        String requestURI = req.getRequestURI();
        Optional<Handler> optional = handlerMapping.stream().filter(handler -> handler.getPattern().matcher(requestURI).matches()).findFirst();
        if(!optional.isPresent()) {
            resp.getWriter().write("404 not found");
            return;
        }
        Handler handler = optional.get();

        String username = req.getParameter("username");
        if(!havePermissions(handler,username)){
            resp.getWriter().write("no permission to visit");
            return;
        }


        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();

        Object[] paraValues = new Object[handler.getParamIndexMapping().size()];

        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            String value = StringUtils.join(stringEntry.getValue(),",");

            if(!handler.getParamIndexMapping().containsKey(stringEntry.getKey())) continue;

            Integer index = handler.getParamIndexMapping().get(stringEntry.getKey());
            paraValues[index] = value;
        }

        Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        if(requestIndex != null) {
            paraValues[requestIndex] = req;
        }

        Integer responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        if(responseIndex != null) {
            paraValues[responseIndex] = resp;
        }

        try {
            if (paraValues.length == 0) {
                handler.getMethod().invoke(handler.getController());//此处无法完成调用，没有8️⃣对象缓存起来，也没有参数
            } else {
                handler.getMethod().invoke(handler.getController(),paraValues);//此处无法完成调用，没有8️⃣对象缓存起来，也没有参数
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private boolean havePermissions(Handler handler, String userName){
        LagouSecurity lagouSecurityClass = handler.getController().getClass().getAnnotation(LagouSecurity.class);

        LagouSecurity lagouSecurityMethod = handler.getMethod().getAnnotation(LagouSecurity.class);

        boolean havePermissions = true;
        //类注解是否有权限
        if(lagouSecurityClass != null){
            havePermissions = Arrays.stream(lagouSecurityClass.value()).anyMatch(s -> s.equals(userName));
        }

        if(!havePermissions){
            return havePermissions;
        }

        //方法注解是否有权限
        if(lagouSecurityMethod != null){
            havePermissions = Arrays.stream(lagouSecurityMethod.value()).anyMatch(s -> s.equals(userName));
        }

        return havePermissions;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1、加载配置文件
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        //2、扫描相关的类、扫描注解
        doScan(properties.getProperty("scanPackage"));
        
        //3、初始化bean对象（实现ioc容器，基于注解）
        try {
            doInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //4、实现依赖注入
        doAutoWired();
        
        //5、构造一个HanlerMapping处理器映射器，将配置好的url和method建立映射关系
        initHanlderMapping();
        
        System.out.println("spring mvc init complte");
    }


    private void initHanlderMapping() {
        if(ioc.isEmpty()) return;

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取ioc中当前遍历的对象的class类型
            Object o = entry.getValue();
            Class<?> aClass = o.getClass();
            if(!aClass.isAnnotationPresent(LagouController.class)){ continue; }

            String baseUrl = "";
            if(aClass.isAnnotationPresent(LagouRequestMapping.class)){
                LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
                baseUrl = annotation.value();
            }

            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if(!method.isAnnotationPresent(LagouRequestMapping.class)) { continue; }

                LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
                String methodUrl = annotation.value();

                String url = baseUrl + methodUrl;

                Handler handler = new Handler(o,method, Pattern.compile(url));

                //计算参数位置信息
                for (int i = 0; i < method.getParameters().length; i++) {
                    Parameter parameter = method.getParameters()[i];
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class){
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),i);
                    }else {
                        handler.getParamIndexMapping().put(parameter.getName(),i);
                    }
                }

                handlerMapping.add(handler);
                //建立url和method之间缓存起来
                //handlerMapping.put(url,method);
            }
        }
    }

    //实现依赖注入
    private void doAutoWired() {
        if(ioc.isEmpty()) return;
        //有对象，再进行依赖注入处理

        //碧莲ioc中所有对象，查看对象中的字段，是否有@LagouAutowired注解，如果有需要维护依赖注入关系
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Object o = entry.getValue();
            Field[] declaredFields = o.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                if(field.isAnnotationPresent(LagouAutowired.class)){
                    field.setAccessible(true);
                    LagouAutowired annotation = field.getAnnotation(LagouAutowired.class);
                    String beanName = annotation.value();
                    if(beanName.isEmpty()){
                        beanName = field.getType().getName();
                    }
                    try {
                        field.set(o,ioc.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }else {
                    continue;
                }
            }
        }
    }

    //ioc容器
    //基于classNames缓存的类的全限定类名，以及反射技术，完成对象创建和管理
    private void doInstance() throws Exception {
        if (classNames.size() == 0) return;

        for (int i = 0; i < classNames.size(); i++) {
            String className = classNames.get(i);

            Class<?> aClass = Class.forName(className);
            //区分controller ，区分service
            if(aClass.isAnnotationPresent(LagouController.class)){
                String simpleName = aClass.getSimpleName();
                String lowerFirst = lowerFirst(simpleName);
                Object o = aClass.newInstance();
                ioc.put(lowerFirst,o);
            }else if(aClass.isAnnotationPresent(LagouService.class)){
                LagouService annotation = aClass.getAnnotation(LagouService.class);
                String simpleName = aClass.getSimpleName();
                String beanName = annotation.value().isEmpty() ? lowerFirst(simpleName) : annotation.value();
                Object o = aClass.newInstance();
                ioc.put(beanName,o);

                Class<?>[] interfaces = aClass.getInterfaces();
                for (int i1 = 0; i1 < interfaces.length; i1++) {
                    Class<?> anInterface = interfaces[i1];
                    ioc.put(anInterface.getName(),o);
                }
            }else {
                continue;
            }
        }
    }

    //扫描类
    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);

        File[] files = pack.listFiles();
        for (File file : files){
            if(file.isDirectory()){
                doScan(scanPackage + "." + file.getName());
            }else if(file.getName().endsWith(".class")){
                String className = scanPackage + "." + file.getName().replaceAll(".class","");
                classNames.add(className);
            }
        }
    }

    //加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String lowerFirst(String str){
        char[] chars = str.toCharArray();
        if('A' <= chars[0] && chars[0] <= 'Z'){
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }
}
